package com.deltabot.networking;

import com.deltabot.logging.Log;

import java.io.*;
import java.net.*;

public class Tools {

    public static String getExternalIP(){
        String IP = null;
        URL url = null;
        try {
            url = new URL("http://whatthehellismyip.com/?ipraw");
        } catch (MalformedURLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(url.openStream()));
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        try {
            IP = in.readLine();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return IP;

    }

    public static String getMacAddress(){
        String macAddress = null;

        try {
            InetAddress address = InetAddress.getLocalHost();
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);

            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {

                    macAddress = "";
                    for (int i = 0; i < mac.length; i++) {
                       macAddress += String.format("%02X%s", mac[i], (i < mac.length -1) ? "-" : "");
                    }

                } else {
                    Log.error("Network Error: Device not accessible");
                }
            } else {
                Log.error("Interface not accessible");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return macAddress;
    }

    public static String getInternalIP(){
        String IP = null;
        try {

            InetAddress i = InetAddress.getLocalHost();
            IP = i.getHostAddress();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return IP;
    }

    public static String getHostName(){
        String HN = null;
        try {

            InetAddress i = InetAddress.getLocalHost();
            HN = i.getHostName();
        }
        catch(Exception e){
            e.printStackTrace();
        }

        if(HN.endsWith(".local")){
            //we have no use for this. We just need to identify this PC on our website (USERNAME@HOSTNAME)
            HN = HN.substring(0, HN.length() - 6);
        }

        return HN;
    }

}
